<template>
  <view class="merchant-home-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <text class="nav-title">商家中心</text>
      <view class="nav-right">
        <button class="switch-btn" @click="switchToCustomer">切换</button>
        <button class="logout-btn" @click="logout">退出</button>
      </view>
    </view>

    <!-- 商家信息卡片 -->
    <view class="merchant-info-card">
      <view class="merchant-header">
        <view class="merchant-logo-wrapper">
          <image 
            v-if="merchantInfo.logo" 
            :src="merchantInfo.logo" 
            class="merchant-logo" 
            mode="aspectFill"
            @error="onLogoError"
          />
          <view v-else class="merchant-logo-placeholder">
            <text class="logo-text">{{ merchantInfo.nameInitial }}</text>
          </view>
        </view>
        <view class="merchant-info">
          <view class="merchant-name">{{ merchantInfo.name }}</view>
          <view class="merchant-desc">{{ merchantInfo.description || '欢迎使用商家管理系统' }}</view>
        </view>
      </view>
    </view>

    <!-- 今日数据概览 -->
    <view class="stats-section">
      <text class="section-title">📊 今日数据</text>
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">{{ statistics.todayOrders }}</text>
          <text class="stat-label">订单数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">¥{{ statistics.todayRevenue }}</text>
          <text class="stat-label">营收</text>
        </view>
        <view class="stat-item highlight">
          <text class="stat-value">{{ statistics.pendingOrders }}</text>
          <text class="stat-label">待处理</text>
        </view>
      </view>
    </view>

    <!-- 待处理订单 -->
    <view class="pending-orders-section" v-if="pendingOrders.length > 0">
      <view class="section-header">
        <text class="section-title">📋 待处理订单</text>
        <text class="view-all" @click="viewAllOrders">查看全部</text>
      </view>
      
      <view 
        class="order-card" 
        v-for="order in pendingOrders" 
        :key="order.id"
        @click="viewOrderDetail(order.id)"
      >
        <view class="order-header">
          <text class="order-no">订单 #{{ order.orderNo }}</text>
          <text class="order-status" :class="order.status">{{ getStatusText(order.status) }}</text>
        </view>
        
        <view class="order-body">
          <view class="order-items">
            <text class="item-name">{{ order.itemsText }}</text>
          </view>
          <view class="order-amount">
            <text class="amount">¥{{ order.totalAmount }}</text>
          </view>
        </view>

        <view class="order-footer" v-if="order.status === 'pending' || order.status === 'paid'">
          <button class="action-btn reject" @click.stop="rejectOrder(order.id)">拒绝</button>
          <button class="action-btn accept" @click.stop="acceptOrder(order.id)">接单</button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="pendingOrders.length === 0 && !loading">
      <text class="empty-icon">📦</text>
      <text class="empty-text">暂无待处理订单</text>
    </view>

    <!-- 快捷操作 -->
    <view class="quick-actions-section">
      <text class="section-title">🚀 快捷操作</text>
      <view class="actions-grid">
        <view class="action-item" @click="goToOrders">
          <text class="action-icon">📋</text>
          <text class="action-label">订单管理</text>
        </view>
        <view class="action-item" @click="goToFoods">
          <text class="action-icon">🍱</text>
          <text class="action-label">商品管理</text>
        </view>
        <view class="action-item" @click="goToReviews">
          <text class="action-icon">💬</text>
          <text class="action-label">评价管理</text>
        </view>
        <view class="action-item" @click="goToSettings">
          <text class="action-icon">⚙️</text>
          <text class="action-label">店铺设置</text>
        </view>
      </view>
    </view>

    <!-- 底部导航 -->
    <view class="bottom-nav">
      <view class="nav-item active">
        <text class="nav-icon">🏠</text>
        <text class="nav-label">首页</text>
      </view>
      <view class="nav-item" @click="goToOrders">
        <text class="nav-icon">📋</text>
        <text class="nav-label">订单</text>
      </view>
      <view class="nav-item" @click="goToFoods">
        <text class="nav-icon">🍱</text>
        <text class="nav-label">商品</text>
      </view>
      <view class="nav-item" @click="goToSettings">
        <text class="nav-icon">⚙️</text>
        <text class="nav-label">设置</text>
      </view>
    </view>
    
    <!-- 自定义弹窗 -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import authService from '../../../services/auth.js'
import merchantService from '../../../services/merchant.js'
import CustomModal from '../../../components/CustomModal.vue'

export default {
  components: {
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      loading: false,
      merchantInfo: {
        logo: '',
        name: '加载中...',
        description: '',
        nameInitial: '店'
      },
      statistics: {
        todayOrders: 0,
        todayRevenue: 0,
        pendingOrders: 0
      },
      pendingOrders: []
    }
  },
  onLoad() {
    this.getStatusBarHeight()
    this.checkMerchantAuth()
    this.loadData()
  },
  onShow() {
    // 每次显示页面时刷新数据
    this.loadData()
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      
      // 设置CSS变量，用于fixed定位计算
      const statusBarHeightPx = this.statusBarHeight + 'px'
      document.documentElement.style.setProperty('--status-bar-height', statusBarHeightPx)
    },

    // 检查商家权限
    checkMerchantAuth() {
      const userInfo = authService.getLocalUserInfo()
      if (!userInfo || userInfo.role !== 'merchant') {
        uni.showToast({
          title: '无权访问商家端',
          icon: 'none'
        })
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }, 1500)
        return
      }

      // 设置商家信息
      if (userInfo.merchantId) {
        this.loadMerchantInfo()
      }
    },

    // 加载所有数据
    async loadData() {
      this.loadStatistics()
      this.loadPendingOrders()
    },

    // 加载商家信息
    async loadMerchantInfo() {
      try {
        const response = await merchantService.getMerchantInfo()
        const data = response.data
        const merchantName = data.name || '我的店铺'
        
        this.merchantInfo = {
          logo: data.logo || '',
          name: merchantName,
          description: data.description || '欢迎使用商家管理系统',
          nameInitial: merchantName.charAt(0).toUpperCase()
        }
      } catch (error) {
        console.error('加载商家信息失败:', error)
        // 失败时使用本地数据
        const userInfo = authService.getLocalUserInfo()
        const merchantName = userInfo.realName || '我的店铺'
        
        this.merchantInfo = {
          logo: '',
          name: merchantName,
          description: '欢迎使用商家管理系统',
          nameInitial: merchantName.charAt(0).toUpperCase()
        }
      }
    },
    
    // Logo加载失败
    onLogoError() {
      console.log('商家Logo加载失败')
      this.merchantInfo.logo = ''
    },

    // 加载统计数据
    async loadStatistics() {
      try {
        // 使用订单统计接口（更实时）
        const response = await merchantService.getOrderStats()
        
        // 注意：todayAmount 单位是分，需要除以100
        this.statistics = {
          todayOrders: response.data.todayCount || 0,
          todayRevenue: response.data.todayAmount ? (response.data.todayAmount / 100).toFixed(2) : '0.00',
          // 待处理订单数 = pending + paid（后端可能只返回 pending）
          pendingOrders: (response.data.pendingCount || 0) + (response.data.paidCount || 0)
        }
        
        console.log('统计数据:', this.statistics)
      } catch (error) {
        console.error('加载统计数据失败:', error)
        this.statistics = {
          todayOrders: 0,
          todayRevenue: '0.00',
          pendingOrders: 0
        }
      }
    },

    // 加载待处理订单
    async loadPendingOrders() {
      this.loading = true
      try {
        // 获取所有订单，然后前端筛选 pending 和 paid 状态
        const response = await merchantService.getOrders({ 
          page: 1,
          pageSize: 20  // 多获取一些，然后筛选
        })
        
        // 格式化订单数据，只保留 pending 和 paid 状态的订单
        const orders = response.data || []
        const pendingAndPaidOrders = orders.filter(order => 
          order.status === 'pending' || order.status === 'paid'
        )
        
        this.pendingOrders = pendingAndPaidOrders
          .slice(0, 3)  // 只显示前3个
          .map(order => {
            // 生成商品列表文本
            const itemsText = order.items && order.items.length > 0
              ? order.items.map(item => `${item.foodName} x${item.quantity}`).join(', ')
              : '暂无商品信息'
            
            return {
              id: order.id,
              orderNo: order.orderNo,
              status: order.status,
              itemsText: itemsText,
              totalAmount: order.totalAmount
            }
          })
        
        // 更新统计数字（使用实际订单数量）
        this.statistics.pendingOrders = pendingAndPaidOrders.length
        
        console.log('待处理订单:', this.pendingOrders)
        console.log('待处理订单总数:', pendingAndPaidOrders.length)
      } catch (error) {
        console.error('加载待处理订单失败:', error)
        this.pendingOrders = []
      } finally {
        this.loading = false
      }
    },

    // 获取状态文本
    getStatusText(status) {
      return merchantService.getOrderStatusText(status)
    },

    // 接单
    async acceptOrder(orderId) {
      this.$refs.customModal.show({
        type: 'confirm',
        title: '确认接单',
        content: '确认接受此订单吗？',
        confirmText: '确认接单',
        cancelText: '取消',
        onConfirm: async () => {
            try {
              await merchantService.acceptOrder(orderId)
              
              uni.showToast({
                title: '接单成功',
                icon: 'success'
              })
              
              // 刷新数据
              setTimeout(() => {
                this.loadData()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: error.message || '接单失败',
                icon: 'none'
              })
            }
        }
      })
    },
    
    // 拒单
    async rejectOrder(orderId) {
      this.$refs.customModal.show({
        type: 'warning',
        title: '拒绝订单',
        content: '确定要拒绝此订单吗？',
        confirmText: '确认拒绝',
        cancelText: '取消',
        showInput: true,
        inputPlaceholder: '请输入拒绝原因（选填）',
        onConfirm: async (inputValue) => {
            try {
              const reason = inputValue || '商家拒绝接单'
              await merchantService.rejectOrder(orderId, reason)
              
              uni.showToast({
                title: '已拒绝订单',
                icon: 'success'
              })
              
              // 刷新数据
              setTimeout(() => {
                this.loadData()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
        }
      })
    },

    // 查看订单详情
    viewOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/merchant/order-detail/order-detail?id=${orderId}`
      })
    },

    // 查看全部订单
    viewAllOrders() {
      uni.navigateTo({
        url: '/pages/merchant/orders/orders?status=pending'
      })
    },

    // 切换到用户端
    switchToCustomer() {
      this.$refs.customModal.show({
        type: 'confirm',
        title: '切换到用户端',
        content: '是否要切换到用户端？',
        confirmText: '确定',
        cancelText: '取消',
        onConfirm: () => {
          uni.reLaunch({
            url: '/pages/home/home'
          })
        }
      })
    },

    // 退出登录
    logout() {
      this.$refs.customModal.show({
        type: 'warning',
        title: '退出登录',
        content: '确定要退出登录吗？',
        confirmText: '确定退出',
        cancelText: '取消',
        onConfirm: () => {
          // 清除本地存储的用户信息和token
          uni.removeStorageSync('jwt_token')
          uni.removeStorageSync('user_info')
          
          uni.showToast({
            title: '已退出登录',
            icon: 'success'
          })
          
          // 延迟一下跳转，让用户看到提示
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            })
          }, 500)
        }
      })
    },

    // 导航到订单管理
    goToOrders() {
      uni.navigateTo({
        url: '/pages/merchant/orders/orders'
      })
    },

    // 导航到商品管理
    goToFoods() {
      uni.navigateTo({
        url: '/pages/merchant/foods/foods'
      })
    },

    // 导航到设置
    goToSettings() {
      uni.navigateTo({
        url: '/pages/merchant/settings/settings'
      })
    },

    // 导航到评价管理
    goToReviews() {
      uni.navigateTo({
        url: '/pages/merchant/reviews/reviews'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.merchant-home-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 140rpx;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

// 顶部导航栏
.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  z-index: 998;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
  flex-shrink: 0;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex-shrink: 0;
}

.switch-btn {
  height: 56rpx;
  padding: 0 20rpx;
  background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
  color: #fff;
  border: none;
  border-radius: 28rpx;
  font-size: 24rpx;
  line-height: 56rpx;
}

.logout-btn {
  height: 56rpx;
  padding: 0 20rpx;
  background: linear-gradient(135deg, #ff4757 0%, #ff6b81 100%);
  color: #fff;
  border: none;
  border-radius: 28rpx;
  font-size: 24rpx;
  line-height: 56rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 71, 87, 0.3);
}

// 商家信息卡片
.merchant-info-card {
  background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
  margin: 20rpx;
  margin-top: calc(var(--status-bar-height) + 88rpx + 20rpx); // 状态栏 + 导航栏 + 间距
  padding: 40rpx 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 20rpx rgba(255, 138, 0, 0.3);
}

.merchant-header {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.merchant-logo-wrapper {
  flex-shrink: 0;
}

.merchant-logo {
  width: 120rpx;
  height: 120rpx;
  border-radius: 20rpx;
  background: rgba(255, 255, 255, 0.2);
  border: 3rpx solid rgba(255, 255, 255, 0.5);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.merchant-logo-placeholder {
  width: 120rpx;
  height: 120rpx;
  border-radius: 20rpx;
  background: rgba(255, 255, 255, 0.25);
  border: 3rpx solid rgba(255, 255, 255, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .logo-text {
    font-size: 48rpx;
    font-weight: 700;
    color: #fff;
  }
}

.merchant-info {
  flex: 1;
  min-width: 0;
}

.merchant-name {
  font-size: 40rpx;
  font-weight: 700;
  color: #fff;
  margin-bottom: 12rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.merchant-desc {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

// 统计数据
.stats-section {
  margin: 20rpx;
}

.section-title {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.stat-item {
  background: #fff;
  padding: 30rpx 20rpx;
  border-radius: 16rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  &.highlight {
    background: linear-gradient(135deg, #ffe0b2 0%, #ffcc80 100%);
  }
}

.stat-value {
  display: block;
  font-size: 36rpx;
  font-weight: 700;
  color: #ff8a00;
  margin-bottom: 8rpx;
}

.stat-label {
  display: block;
  font-size: 24rpx;
  color: #666;
}

// 待处理订单
.pending-orders-section {
  margin: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.view-all {
  font-size: 24rpx;
  color: #ff8a00;
}

.order-card {
  background: #fff;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.order-no {
  font-size: 26rpx;
  font-weight: 600;
  color: #333;
}

.order-status {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  
  &.pending {
    background: #fff3e0;
    color: #ff8a00;
  }
}

.order-body {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.item-name {
  flex: 1;
  font-size: 24rpx;
  color: #666;
}

.amount {
  font-size: 28rpx;
  font-weight: 700;
  color: #ff4757;
}

.order-footer {
  display: flex;
  gap: 16rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-btn {
  flex: 1;
  height: 64rpx;
  border-radius: 32rpx;
  font-size: 26rpx;
  border: none;
  
  &.reject {
    background: #fff;
    color: #666;
    border: 2rpx solid #ddd;
  }
  
  &.accept {
    background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
    color: #fff;
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 80rpx 0;
}

.empty-icon {
  display: block;
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

// 快捷操作
.quick-actions-section {
  margin: 20rpx;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.action-item {
  background: #fff;
  padding: 40rpx 20rpx;
  border-radius: 16rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.action-icon {
  display: block;
  font-size: 48rpx;
  margin-bottom: 12rpx;
}

.action-label {
  display: block;
  font-size: 24rpx;
  color: #333;
}

// 底部导航
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-item {
  text-align: center;
  
  &.active {
    .nav-icon {
      font-size: 44rpx;
    }
    .nav-label {
      color: #ff8a00;
      font-weight: 600;
    }
  }
}

.nav-icon {
  display: block;
  font-size: 40rpx;
  margin-bottom: 6rpx;
}

.nav-label {
  display: block;
  font-size: 22rpx;
  color: #666;
}
</style>

